<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-table v-loading="loading" class="table-data" :data="form.fundExpenseList" border>
            <el-table-column :label="$t('申请标题')" align="center" prop="actTitle" min-width="200" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.actTitle'" :rules="rules.actTitle">
                  <el-input
                    v-model="scope.row.actTitle"
                    :placeholder="$t('申请标题')"
                    show-word-limit
                    :maxlength="100"
                    @paste.native="pasteMe($event, scope.$index, 'actTitle')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('费用类型')" align="center" prop="typesFee" min-width="140" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.typesFee'" :rules="rules.typesFee">
                  <el-select v-model="scope.row.typesFee" filterable :placeholder="$t('费用类型')" @paste.native="pasteMe($event, scope.$index, 'typesFee')">
                    <el-option
                      v-for="dict in typesFeeOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('发生时间')" align="center" prop="applyTime" show-overflow-tooltip min-width="180">
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.applyTime'" :rules="rules.applyTime">
                  <DatePicker
                    v-model="scope.row.applyTime"
                    :placeholder="$t('发生时间')"
                    @paste.native="pasteMe($event, scope.$index, 'applyTime')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('费用金额(元)')" header-align="center" min-width="160" align="right" prop="amountMoney" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.amountMoney'" :rules="rules.amountMoney">
                  <Money v-model="scope.row.amountMoney" unit="" :placeholder="$t('费用金额(元)')" @paste.native="pasteMe($event, scope.$index, 'amountMoney')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('类型')" align="center" min-width="100" prop="type" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.type'" :rules="rules.type">
                  <el-select v-model="scope.row.type" :placeholder="$t('类型')" @paste.native="pasteMe($event, scope.$index, 'type')">
                    <el-option
                      v-for="dict in typeOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('费用归属')" align="center" min-width="150" prop="costAttribution" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.costAttribution'" :rules="rules.costAttribution">
                  <el-select v-model="scope.row.costAttribution" :placeholder="$t('费用归属')" @paste.native="pasteMe($event, scope.$index, 'costAttribution')">
                    <el-option
                      v-for="dict in costAttributionOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('分摊项目')" align="center" min-width="130" prop="shareItem" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.costAttribution === 'deal'" :prop="'fundExpenseList.' + scope.$index + '.shareItem'" :rules="rules.shareItem">
                  <el-select v-model="scope.row.shareItem" filterable :placeholder="$t('分摊项目')" @paste.native="pasteMe($event, scope.$index, 'shareItem')">
                    <el-option
                      v-for="dict in shareItemOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('费用明细')" min-width="220" align="center" prop="costsThat" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :prop="'fundExpenseList.' + scope.$index + '.costsThat'">
                  <el-input
                    v-model="scope.row.costsThat"
                    autosize
                    type="textarea"
                    :placeholder="$t('费用明细')"
                    maxlength="2000"
                    @paste.native="pasteMe($event, scope.$index, 'costsThat')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" min-width="100" align="center" fixed="right" class-name="cellHeight">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete" style="cursor: pointer" @click="deleteHandler(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
          <!--          <el-dropdown style="margin-top: 10px;" split-button type="primary" @click="addHandler">-->
          <!--            {{ $t('新增') }}-->
          <!--            <el-dropdown-menu slot="dropdown">-->
          <!--              <el-dropdown-item command="5">{{ $t('添加5行') }}</el-dropdown-item>-->
          <!--              <el-dropdown-item command="10">{{ $t('添加10行') }}</el-dropdown-item>-->
          <!--              <el-dropdown-item command="15">{{ $t('添加15行') }}</el-dropdown-item>-->
          <!--              <el-dropdown-item command="20">{{ $t('添加20行') }}</el-dropdown-item>-->
          <!--              <el-dropdown-item command="30">{{ $t('添加30行') }}</el-dropdown-item>-->
          <!--            </el-dropdown-menu>-->
          <!--          </el-dropdown>-->
          <el-dropdown style="margin-top: 10px;" size="small" class="dropdown" split-button type="primary" @command="handleCommand" @click="addHandler">
            {{ $t('添加') }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="5">{{ $t('添加5行') }}</el-dropdown-item>
              <el-dropdown-item command="10">{{ $t('添加10行') }}</el-dropdown-item>
              <el-dropdown-item command="15">{{ $t('添加15行') }}</el-dropdown-item>
              <el-dropdown-item command="20">{{ $t('添加20行') }}</el-dropdown-item>
              <el-dropdown-item command="30">{{ $t('添加30行') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--      &lt;!&ndash; 使用流程：保存，保存并启动流程，取消 三个按钮&ndash;&gt;-->
      <!--      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" has-permi="fund:expense" :menu-key="menuKey" />-->
      <!--      &lt;!&ndash;未使用流程：保存 取消按钮&ndash;&gt;-->
      <save-btn has-permi="fund:expense" />
    </div>
  </div>
</template>

<script>
import { saveBatchFundExpense } from '@/api/fund/expense/fundExpense'
    import { getFdSubjectList } from '@/api/fd/config/getTypeMain'
    import { getFundName } from '@/api/fund/fundBase'
    import { moneyFormat } from '@/utils/ruoyi'
    import { listDealInvestmentAll } from '@/api/deal/investment/dealInvestment.js'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    export default {
        components: {
        },
        data() {
            return {
                // 菜单标识
                menuKey: 'fund_expense',
                // 是否配置了流程
                useProcess: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单参数
                form: {
                  // 费用明细
                  fundExpenseDetailList: [],
                  fileList: undefined
                },
                // 表单校验
                rules: {
                  typesFee: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  amountMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  shareItem: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  costAttribution: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 付款大类
                getFdSubjectList: [],
                // 上传文件
                fileList: undefined,
                infoOpen: false,
                typesFeeOptions: [],
                costAttributionOptions: [],
                // 是否显示上传按钮
                isShowUploadBtn: true,
                fymxLoading: false,
                deptOptions: [],
                // 上传路径
                uploadUrl: undefined,
                // 是否开启费用明细, 后台也需要去掉if
                whetherToOpenExpenseDetails: false,
                // 分摊项目
                shareItemOptions: [],
              // 现金流类型
              typeOptions: [],
              thatFundId: ''
            }
        },
        created() {
            // 查询是否配置了流程
            this.getUseProcess()
            // 付款大类
            getFdSubjectList('expense').then(response => {
              this.getFdSubjectList = this.changeSubjectList(response.data)
            })
            // 费用类型
            this.getDicts('fund_expense_type_fee').then(response => {
              this.typesFeeOptions = response.data
            })
            // 费用归属
            this.getDicts('fund_expense_cost_attribution').then(response => {
              this.costAttributionOptions = response.data
            })
            // 现金流类型
            this.getDicts('fund_expense_type').then(response => {
              this.typeOptions = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            changeSubjectList(val) {
              const arr = []
              if (val.length !== 0) {
                val.forEach(item => {
                  const obj = {}
                  obj.value = item.value
                  obj.label = this.$t(item.label)
                if (item.children && item.children.length > 0) {
                    obj.children = this.changeSubjectList(item.children)
                  }
                  arr.push(obj)
                })
              }
              return arr
            },
            // 初始化数据
            init() {
              this.loading = true
              this.thatFundId = this.$route.query.id
              this.reset()
              this.apportionmentItemSelect()
              this.loading = false
            },
            changeFund() {
                this.thatFundId = this.form.fundId
                this.apportionmentItemSelect()
            },
            // 表单重置
            reset() {
                this.form = {
                  fundExpenseList: []
                }
                try {
                  this.resetForm('form')
                } catch (e) {
                  console.log(e)
                }
            },
            // 分摊项目下拉
            apportionmentItemSelect() {
              this.shareItemOptions = []
              var fundId = this.form.fundId
              if (fundId === undefined || fundId === null || fundId === '') {
                fundId = this.thatFundId
              }
              listDealInvestmentAll({ investorId: fundId }).then(response => {
                if (response.data !== null && response.data !== undefined) {
                  response.data.forEach(item => {
                    const option = {
                      dictLabel: item.dealName,
                      dictValue: item.dealId
                    }
                    this.shareItemOptions.push(option)
                  })
                }
              })
            },
            handleCommand(command) {
              this.generateData(command)
            },
          generateData(command) {
            for (let i = 0; i < command; i++) {
              this.addHandler()
            }
          },
            addHandler() {
                var obj = {
                  id: undefined,
                  fundId: this.thatFundId,
                  typesFee: undefined,
                  applyTime: new Date(),
                  amountMoney: undefined,
                  costAttribution: 'GTFT',
                  shareItem: undefined,
                  costsThat: undefined,
                  type: 'SJ'
                }
                if (!(this.form.fundExpenseList instanceof Array)) {
                  this.form.fundExpenseList = []
                }
                this.form.fundExpenseList.push(obj)
            },
            deleteHandler(index) {
                this.form.fundExpenseList.splice(index, 1)
            },
            pasteMe(event, index, field) {
                this.$forceUpdate()
                event.srcElement.blur()
                var fields = ['actTitle', 'typesFee', 'applyTime', 'amountMoney', 'type', 'costAttribution', 'shareItem', 'costsThat']
                const source = event.clipboardData.getData('Text')
                var rows = source.split('\n')
                var arr = []
              for (let i = 0; i < rows.length; i++) {
                var columns = ''
                if (rows[i]) {
                  // 拆分列
                  columns = rows[i].split('\t')
                  arr.push(columns)
                }
              }

              var idx = fields.findIndex(item => item === field)
              var nFields = []

              if (idx || idx === 0) {
                nFields = fields.splice(idx, fields.length)
              }

              var containsField = ['typesFee', 'type', 'costAttribution', 'applyTime', 'shareItem']

              if (arr.length === 1) {
                // 一行数据
                arr[0].forEach((v, i) => {
                  nFields.forEach((n, j) => {
                    if (v && i === j) {
                      // 转换为字典值
                      this.labelToDict(v, index, n)
                      // 转换日期
                      this.parseDate(v, index, n)
                      // 转换项目
                      this.parseDeal(v, index, n)

                      if (!containsField.includes(n)) {
                        if (n === 'amountMoney') {
                          // this.form.fundExpenseList[index][n] = isNaN(v) ? undefined : Number(v)
                          this.$set(this.form.fundExpenseList[index], n, isNaN(v) ? undefined : Number(v))
                        } else {
                          // this.form.fundExpenseList[index][n] = v
                          this.$set(this.form.fundExpenseList[index], n, v)
                        }
                      }
                    }
                  })
                })
              } else if (arr.length > 1) {
                // 多行
                var dataArr = []
                arr.forEach((item) => {
                  var obj = {}
                  item.forEach((v, j) => {
                    nFields.forEach((field, n) => {
                      if (j === n) {
                        obj[field] = v
                      }
                    })
                  })
                  dataArr.push(obj)
                })

                dataArr.forEach((item, ind) => {
                  for (const key in item) {
                    this.labelToDict(item[key], index + ind, key)
                    this.parseDate(item[key], index + ind, key)
                    this.parseDeal(item[key], index + ind, key)

                    if (!containsField.includes(key)) {
                      if (key === 'amountMoney') {
                        this.$set(this.form.fundExpenseList[index + ind], key, isNaN(item[key]) ? undefined : Number(item[key]))
                      } else {
                        this.$set(this.form.fundExpenseList[index + ind], key, item[key])
                      }
                    }
                  }
                })
              }
            },
            labelToDict(dict, index, field) {
              if (dict) {
                dict = dict.trim()
              }
              var dictData = null
              switch (field) {
                case 'typesFee':
                  dictData = this.typesFeeOptions.find(item => item.dictLabel === dict)
                  this.form.fundExpenseList[index][field] = dictData ? dictData.dictValue : undefined
                  break
                case 'type':
                  dictData = this.typeOptions.find(item => item.dictLabel === dict)
                  this.form.fundExpenseList[index][field] = dictData ? dictData.dictValue : undefined
                  break
                case 'costAttribution':
                  dictData = this.costAttributionOptions.find(item => item.dictLabel === dict)
                  this.form.fundExpenseList[index][field] = dictData ? dictData.dictValue : undefined
                  break
              }
            },
          parseDate(value, index, field) {
            if (value) {
              value = value.trim()
            }
            if (field === 'applyTime') {
              var date = this.parseTime(value)
              this.form.fundExpenseList[index][field] = date === '1970-01-01' ? undefined : date
            }
          },
            parseDeal(value, index, field) {
              if (value) {
                value = value.trim()
              }
              if (field === 'shareItem') {
                var type = this.form.fundExpenseList[index]['costAttribution']
                var deal = this.shareItemOptions.find(item => item.dictLabel === value)
                this.form.fundExpenseList[index][field] = deal && type === 'deal' ? deal.dictValue : undefined
              }
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.batchFormOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                if (this.$parent.$parent.batchFormOpen !== undefined) {
                  this.$parent.$parent.batchFormOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
                if (this.$parent.$parent.getStatisticalList !== undefined) {
                  this.$parent.$parent.getStatisticalList()
                }
                if (this.$parent.$parent.getChartData !== undefined) {
                  this.$parent.$parent.getChartData()
                }
                if (this.$parent.$parent.getChartDataByLp !== undefined) {
                  this.$parent.$parent.getChartDataByLp()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
              console.log(this.$refs['form'], this.form)
              this.$refs['form'].validate(valid => {
                // 验证数据
                if (valid) {
                  // 弹出遮罩层
                  this.loading = true

                  // 保存数据
                  saveBatchFundExpense(this.form).then(response => {
                    if (response.code === 200) {
                      this.msgSuccess(this.$t('保存成功'))
                      // 关闭form页面
                      this.closeForm()
                    } else {
                      this.msgError(response.msg)
                      this.loading = false
                    }
                  }).catch(() => {
                    this.loading = false
                  })
                } else {
                  this.locationError(document)
                }
              })
            },
            // 启动流程
            startProcess: async function(data) {
               var fundName = await getFundName(this.thatFundId)
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + fundName + '」' + ': ' + this.form.actTitle + '(' + moneyFormat(data.amountMoney) + this.$t('元') + ')'
               // 业务表名
               processData.dataTable = 'fund_expense'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/fund/expense/fundExpenseForm'
               processData.viewPath = '@/views/fund/expense/fundExpenseView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
            },
            // 预览附件
            onlinePreview(row) {
              this.$refs.OnlinePreview.onlinePreviewFile(row.id)
            },
            // 打开流程详情页面 查看OA 报销
            openProcessInfoForm(actId) {
              if (actId) {
                this.infoOpen = true
                this.$nextTick(() => {
                  this.$refs.processInfoForm.init({ actId: actId })
                })
              } else {
                this.msgError(this.$t('流程ID为空,不能查看流程信息'))
              }
            },
            // 获取是否使用流程
            getUseProcess() {
              getMenuProcess('fund_expense').then(response => {
                this.useProcess = !!response.data
              })
            }
        }
    }
</script>

<style scoped>
/deep/.table-data .el-form-item{
  min-height: unset;
}
/deep/.table-data .el-form-item.is-error{
  min-height: 55px;
}
/deep/.dropdown .el-button-group .el-button {
  height: 32.5px;
  vertical-align: middle;
}
/deep/td.cellHeight{
  height: 70px;
}
</style>
